//
//  AskController.m
//  Finance
//
//  Created by 郝旭珊 on 2017/12/27.
//  Copyright © 2017年 郝旭珊. All rights reserved.
//


//选择相册多图上传
#import "AskController.h"
#import <CTAssetsPickerController/CTAssetsPickerController.h>


@interface AskController ()<CTAssetsPickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIView *imageContentView;
@property (nonatomic, strong) UIButton *callCameraButton;
@property (nonatomic, strong) NSArray *imageDatas;
@property (nonatomic, assign) CGFloat imageW;

@end

@implementation AskController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"提问";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"递交" style:UIBarButtonItemStylePlain target:self action:@selector(submit)];
    
    self.imageW = (SCREEN_WIDTH-MARGIN*5)/4;
    [self setupImageUI];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)setupImageUI{
    UIButton *callCameraButton = [UIButton buttonWithFrame:CGRectMake(MARGIN, MARGIN, self.imageW, self.imageW) title:@"+照片(选填)" font:FONT_NORMAL titleColor:GRAYCOLOR_TEXT_LIGHT backgroundColor:[UIColor clearColor] target:self actionName:@"callCamera"];
    callCameraButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    callCameraButton.layer.borderColor = GRAYCOLOR_BORDER.CGColor;
    callCameraButton.layer.borderWidth = 1;
    self.callCameraButton = callCameraButton;
    [self.imageContentView addSubview:callCameraButton];
    [self.imageContentView setHeight:callCameraButton.maxY+MARGIN];
    
}


#pragma mark - 响应事件

- (void)submit{
    
}


//在工程对应的plist文件内添加“Privacy - Photo Library Usage Description”
//"Privacy - Camera Usage Description"
- (void)callCamera {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
        //判断相机权限
        if (status != PHAuthorizationStatusAuthorized) return;
        dispatch_async(dispatch_get_main_queue(), ^{
            CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
            picker.delegate =self;
            // 显示选择的索引
            picker.showsSelectionIndex =YES;
            /* // set default album (Camera Roll)
             picker.defaultAssetCollection = PHAssetCollectionSubtypeSmartAlbumUserLibrary;
             
             // to present picker as a form sheet in iPad
             if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
             picker.modalPresentationStyle = UIModalPresentationFormSheet;*/
            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
                picker.modalPresentationStyle = UIModalPresentationFormSheet;
            }
            // 设置相册的类型：相机胶卷 +自定义相册
            picker.assetCollectionSubtypes =@[@(PHAssetCollectionSubtypeSmartAlbumUserLibrary),
                                              @(PHAssetCollectionSubtypeAlbumRegular)];
            // 不需要显示空的相册
            picker.showsEmptyAlbums = NO;
            [self presentViewController:picker animated:YES completion:nil];
        });
    }];
}


#pragma mark - CTAssetsPickerControllerDelegate

- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    NSInteger max =9;
    if (picker.selectedAssets.count >= max) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"message:[NSString stringWithFormat:@"最多选择%zd张图片", max] preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil]];
        [picker presentViewController:alert animated:YES completion:nil];
        // 这里不能使用self来modal别的控制器，因为此时self.view不在window上
        return NO;
    }
    
    return YES;
}


-(void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    // 关闭图片选择界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSMutableArray *mImageDatas = [NSMutableArray array];
    for (NSInteger i =0; i < assets.count; i++) {
        // 基本配置
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.resizeMode = PHImageRequestOptionsResizeModeExact;
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        PHAsset *asset = assets[i];
        // 获取图片
        [[PHImageManager defaultManager]requestImageDataForAsset:asset options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
            
            [mImageDatas addObject:imageData];
            
            if (i==assets.count-1){
                self.imageDatas = mImageDatas;
                [self addImage];
            }
            
        }];
        
        
    }
    
}


- (void)addImage{
    [self.imageDatas enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImage *image = [UIImage imageWithData:obj];
        UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
        CGFloat imageX = (idx%4)*(_imageW+MARGIN)+MARGIN;
        CGFloat imageY = (idx/4)*(_imageW+MARGIN)+MARGIN;
        imageView.frame = CGRectMake(imageX,imageY, self.imageW, self.imageW);
        [self.imageContentView addSubview:imageView];
        
        if (idx == self.imageDatas.count-1){
            [self.imageContentView setHeight:imageView.maxY+MARGIN];
        }
    }];
    
    if (self.imageDatas.count >= 9){
        return;
    }
    long int i = self.imageDatas.count;
    CGFloat imageX = (i%4)*(_imageW+MARGIN)+MARGIN;
    CGFloat imageY = (i/4)*(_imageW+MARGIN)+MARGIN;
    self.callCameraButton.frame = CGRectMake(imageX,imageY, self.imageW, self.imageW);
    
}



@end
